import json
import os


def load_playlog():
    """
        Load the playlog from a JSON file and update the music database.

        This function performs the following steps:
        1. Reads the playlog data from '../score/playlog.json'.
        2. Checks if 'music.json' exists. If not, initializes an empty music dictionary.
        3. Updates the music dictionary with new songs from the playlog.
        4. Writes the updated music dictionary back to 'music.json'.

        Raises:
            FileNotFoundError: If the playlog file is not found.
            json.JSONDecodeError: If there is an error decoding the JSON files.
        """
    with open('../score/playlog.json', 'r', encoding='utf-8') as f:
        playlog = json.load(f)

    # update misic database
    # if music.json not exists, music = {}
    if not os.path.exists('music.json'):
        music = {}
    else:
        with open('music.json', 'r', encoding='utf-8') as f:
            music = json.load(f)
    for song in playlog['data']['data']:
        if song['music']['name'] not in music:
            music[song['music']['name']] = {
                'jacket': song['music']['jacket'],
                'artist': song['music']['artist'],
            }
    with open('music.json', 'w', encoding='utf-8') as f:
        json.dump(music, f, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    load_playlog()
